import { question as QuestionApi } from '../../../../../config/request.js';
import { resources, excelUtil as ExcelUtil } from '../../../../../util';

const qType = resources.qType;

module.exports = {
    name: 'questions',
    data() {
        return {
            downloadName: '题目列表-' + new Date().getTime() + '.xlsx',
            addFormVisible: false,
            questionVisible: false,
            codeVisible: false,
            questionForm: {
                type: '1', //题目类型
                main: '', //题干
                options: [], //选项
                title: "新增问题",
                isupdate: false,
                hasScore: false,
                score: 0,
                remark: ''
            },
            questionData: {},
            codeData: {},
            tableData: [],
            type: {
                info: { prop: 'type', label: '类型', sortable: true },
                filter: {},
                style: { align: 'center' }
            },
            fields: [{
                    info: { prop: 'main', label: '题干', sortable: false },
                    filter: {},
                    style: { align: 'center' }
                },
                // {
                //     info: { prop: 'options', label: '选项' },
                //     filter: {},
                //     style: { align: 'center' }
                // },
                {
                    info: { prop: 'remark', label: '备注', sortable: false },
                    filter: {},
                    style: { align: 'center' }
                }
            ]
        }
    },

    methods: {
        downloadExl() {
            this.downloadName = '题目列表-' + new Date().getTime() + '.xlsx';
            var tableData = this.tableData;
            var data = ExcelUtil.formatterData(tableData, ['status'], { 'type': '题目类型', 'main': '题干', 'options': '选项' }, {
                'options': function(options) {
                    var string = '';
                    if (options) {
                        try {
                            options = JSON.parse(options)
                            for (var i = 0; i < options.length; i++) {
                                string += ('选项' + (i + 1) + ':' + options[i]['value'] + ';');
                            }
                        } catch (err) {
                            string = ''
                            options = '';
                        }
                    }
                    return string;
                }
            });
            ExcelUtil.downloadExl(this.downloadName, data);
        },
        questionTypes() { return qType },
        formatterType(item) {
            for (let i in qType) {
                if (item.type == qType[i].value) {
                    return qType[i].label
                }
            }
        },
        formatterTypeByNumber(type) {
            for (let i in qType) {
                if (type == qType[i].value) {
                    return qType[i].label
                }
            }
        },

        /** 提交表单 */
        submitForm(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    const formData = this[formName]
                    if (formData.isupdate) {
                        this.updateQuestion(formData);
                    } else {
                        this.addQuestion(formData);
                    }
                } else {
                    return false;
                }
            });
        },

        addQuestion(formData) {
            if (formData.hasScore) {
                formData.options = [{ hasScore: true, score: formData.score }];
            }
            delete formData.token;
            QuestionApi.createQuestion.call(this, formData,
                (data) => {
                    this.tableData.push(data['question']);
                    this.$message.success('添加问题成功 ！！');
                    this.addFormVisible = false;
                    this.$refs['questionForm'].resetFields();
                    this.questionForm = {
                        type: '1',
                        main: '',
                        options: [],
                        title: "新增问题",
                        isupdate: false,
                        hasScore: false,
                        score: 0,
                        remark: ''
                    };
                },
                (msg) => {
                    this.$message.error('添加问题失败 ！！');
                })
        },

        updateQuestion(formData) {
            let dealForm = this._dealForm(formData);
            QuestionApi.updateQuestion.call(this, dealForm,
                (data) => {
                    this.$message.success('修改问题成功 ！！');
                    this.initData();
                    this.addFormVisible = false;
                    this.$refs['questionForm'].resetFields();
                    this.questionForm = {
                        type: '1',
                        main: '',
                        options: [],
                        title: "新增问题",
                        isupdate: false,
                        hasScore: false,
                        score: 0,
                        remark: ''
                    }
                },
                (msg) => {
                    this.$message.error('修改问题失败 ！！');
                })
        },

        _dealForm(formData) {
            let dealForm = {}
            dealForm.id = formData.id
            dealForm.main = formData.main
            dealForm.remark = formData.remark
            dealForm.options = []
            for (let i in formData.options) {
                dealForm.options.push({
                    id: formData.options[i].id,
                    value: formData.options[i].value,
                    checked: formData.options[i].checked,
                    hasScore: formData.options[i].hasScore,
                    score: formData.options[i].score
                });
            }
            return dealForm;
        },

        /** 添加选项 */
        addOption() {
            //如果是问答题
            if (this.questionForm.type == 4) {
                this.$message.error('问答题不允许有选项 !!');
                return;
            }
            if (this.questionForm.type == 5) {
                this.$message.error('选择日期不允许有选项 !!');
                return;
            }
            if (this.questionForm.type == 6) {
                this.$message.error('选择时间不允许有选项 !!');
                return;
            }
            if (this.questionForm.type == 7) {
                this.$message.error('选择数字不允许有选项 !!');
                return;
            }
            //如果是判断题目
            if (this.questionForm.type == 3) {
                if (this.questionForm.options.length == 2) {
                    this.$message.error('判断题只允许有两个选项 !!');
                    return;
                }
            }

            //添加
            let id = this.questionForm.options.length + 1
            this.questionForm.options.push({
                value: '',
                checked: false,
                id: id,
                hasScore: false,
                score: 0
            });
        },

        /** 删除选项 */
        removeOption(item) {
            var index = this.questionForm.options.indexOf(item)
            if (index !== -1) {
                this.questionForm.options.splice(index, 1)
            }
        },

        /** 删除 */
        onDeleteQuestion(question) {
            this.$confirm('是否确认删除该题目？', '提示', {
                cancelButtonText: '取消',
                confirmButtonText: '确定',
                type: 'warning'
            }).then(_ => {
                QuestionApi.deleteQuestion.call(this, question.id, (result) => {
                    let index = this.tableData.indexOf(question)
                    if (index !== -1) {
                        this.tableData.splice(index, 1);
                    }
                    this.$message.success('删除成功 ？');
                })
            }).catch((err) => {
                this.$message.error(err);
            });
        },
        /**
         * 显示添加问题的对话框
         */
        onAddQuestion() {
            this.questionForm = {
                type: 1, //题目类型
                main: '', //题干
                options: [], //选项
                title: "新增问题",
                isupdate: false,
                hasScore: false,
                score: 0,
                remark: ''
            };
            this.addFormVisible = true;
        },

        /** 修改题目 */
        onEditQuestion(question) {
            // console.log('question', question);
            var questionTemp = {};
            Object.assign(questionTemp, question);
            questionTemp.options = JSON.parse(questionTemp.options);
            console.log(questionTemp)
            this.questionForm = questionTemp;
            // console.log(question);
            // for (let i in qType) {
            //     if (qType[i].value == question.type) {
            //         this.questionForm.type = qType[i].label
            //         break;
            //     }
            // }
            this.questionForm.isupdate = true;
            this.questionForm.title = "修改问题"
            this.addFormVisible = true;
        },
        checkLevel() {
            var user = this.$store.state.user.userinfo;
            // console.log('user', user);
            return user && user.level == 1;
        },
        /**
         * 预览问题
         * @param {any} question 
         */
        previewQuestion(question) {
            this.questionData = {
                type: question.type,
                main: question.main,
                options: JSON.parse(question.options),
                remark: question.remark
            };
            this.questionVisible = true;
        },
        /**
         * 查看代码
         * @param {any} question 
         */
        previewCode(question) {
            this.codeData = { code: JSON.stringify(question) };
            this.codeVisible = true;
        },

        initData() {
            QuestionApi.queryAll.call(this, (data) => {
                // console.log(data.questions);
                this.tableData = data.questions;
            })
        }
    },

    mounted: function() {
        this.initData();
    }
}